<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="riskPoint">
        <el-input v-model="queryParams.riskPoint" placeholder="请输入风险点" clearable size="middle" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="" prop="riskType">
        <el-select v-model="queryParams.riskType" placeholder="请选择风险类型" clearable size="middle" @keyup.enter.native="handleQuery">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['biz:risk-info:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
     <!-- 风险列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="风险点" align="center" prop="riskPoint" />
      <el-table-column label="类型" align="center" prop="riskType">
        <template slot-scope="scope" >
          <span v-if="scope.row.riskType == 1">基础管理</span>
          <span v-if="scope.row.riskType == 2">作业活动</span>
          <span v-if="scope.row.riskType == 3">设备设施</span>
        </template>
      </el-table-column>
      <el-table-column label="可能发生的事故类型" align="center" prop="accidentTypeId">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ACCIDENT" :value="scope.row.accidentTypeId" />
        </template>
      </el-table-column>
      <el-table-column label="区域位置" align="center" prop="regionSite" />
      <el-table-column label="所属单位" align="center" prop="companyName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" >
          <el-button  size="mini" type="text" icon="el-icon-edit" @click="openHazardResource(scope.row)"
                     v-hasPermi="['biz:risk-info:update']">危险源</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <el-dialog :title="hazardTitle" :visible.sync="hazardOpen" width="60%" append-to-body>
      <HazardResource :riskId="riskId" ></HazardResource>
    </el-dialog>

    <!-- 风险导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click='downloadTemplate'>下载模板</el-link>
           <!-- @click="importTemplate" -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRiskInfoPage, exportRiskInfoExcel2,downRiskTemplate} from "@/api/biz/riskInfo";
import { getDeptByCurrentUser } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import HazardResource from "@/views/biz/hazardResource"
import {getBaseHeader} from "@/utils/request";
export default {
  name: "RiskControlList",
  components: {
    HazardResource
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 风险数据列表
      list: [],
      // 弹出层标题
      title: "",
      //危险源弹出层标题
      hazardTitle: "",
      // 是否显示弹出层
      open: false,
      // 是否显示危险源弹出层
      hazardOpen: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        riskPoint: null,
        riskType: null
      },
      //风险类型下拉框
      options: [{
          value: '1',
          label: '基础管理'
        }, {
          value: '2',
          label: '作业活动'
        }, {
          value: '3',
          label: '设备设施'
        }],
      riskId:'',

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: getBaseHeader(),
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/admin-api/' + "/biz/riskInfo/import"
      }
    };
  },
  created() {
    this.getList();
  },
  mounted(){
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = {...this.queryParams};
      // 执行查询
      getRiskInfoPage(params).then(response => {
        this.list = response.list;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
     /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "风险导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    // importTemplate() {
    //   importTemplate().then(response => {
    //     this.$download.excel(response, '用户导入模板.xls');
    //   });
    // },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      if (response.code !== 0) {
        this.$modal.msgError(response.msg)
        return;
      }
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 拼接提示语
      let data = response.data;
      let text = '';
      // for (const username of data.createUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      // text += '<br />更新成功数量：' + data.updateUsernames.length;
      // for (const username of data.updateUsernames) {
      //   text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + username;
      // }
      text += '<br />更新失败数量：' + Object.keys(data.failureRisknames).length;
      for (const riksname in data.failureRisknames) {
        text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;' + riksname + '：' + data.failureRisknames[riksname];
      }
      this.$alert(text, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
     openHazardResource(row){
      //打开危险源
      this.riskId = row.id;
      this.hazardTitle = '危险源';
      this.hazardOpen = true;
    },
    // 下载模板
    downloadTemplate() {
      // 执行导出
      downRiskTemplate().then(response => {
          this.$download.excel(response, '风险模板.xls');
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeIdentificatDate, 'identificatDate');
      this.addBeginAndEndTime(params, this.dateRangeControlDate, 'controlDate');
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, 'createTime');
      // 执行导出
      this.$modal.confirm('是否确认导出所有风险数据数据项?').then(() => {
          this.exportLoading = true;
          return exportRiskInfoExcel2(params);
        }).then(response => {
          console.log(response)
          this.$download.excel(response, '风险数据.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
  }
};
</script>
